import { useState } from "react";
import { useDispatch } from "react-redux";
import { addTodo } from '../store/actions/todos'
const TodoHeader = () => {
  // 1. 受控组件，监听按键，判断是否回车，判断是否为空
  // 2. 分发action（action type--->action---->readucer）
  // 3. 情况输入内容
  const [text, setText] = useState("");
  const dispatch = useDispatch()
  const onKeyDown = (e) => {
    if (e.keyCode !== 13) return;
    if (text.trim() === "") return;
    dispatch(addTodo(text))
    setText('')
  };

  return (
    <header className="header">
      <h1>todos</h1>
      <input
        className="new-todo"
        placeholder="What needs to be done?"
        autoFocus
        value={text}
        onChange={(e) => setText(e.target.value)}
        onKeyDown={onKeyDown}
      />
    </header>
  );
};
export default TodoHeader;
